package com.sskj.api.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.sskj.api.handler.introspector.WithDomainAnnotationIntrospector;
import com.sskj.api.properties.FileProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ObjectMapperConfig {

    @Autowired
    private FileProperties fileProperties;

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, new NumberSerializer(Long.class) {
            @Override
            public void serialize(Number value, JsonGenerator g, SerializerProvider provider) throws IOException {
                g.writeString(value.toString());
            }
        });
        simpleModule.addSerializer(long.class, new NumberSerializer(long.class) {
            @Override
            public void serialize(Number value, JsonGenerator g, SerializerProvider provider) throws IOException {
                g.writeString(value.toString());
            }
        });
        objectMapper.registerModule(simpleModule);

        // 支持Java8+ 的 java.time 类型
        objectMapper.registerModule(new JavaTimeModule());


        AnnotationIntrospector annotationIntrospector = objectMapper.getSerializationConfig().getAnnotationIntrospector();
        WithDomainAnnotationIntrospector withDomainAnnotationIntrospector = new WithDomainAnnotationIntrospector(fileProperties.getDomain());
        objectMapper.setAnnotationIntrospector(AnnotationIntrospector.pair(annotationIntrospector, withDomainAnnotationIntrospector));

        return objectMapper;
    }
}
